<template>
  <div class="app-container">

    

    <!-- 收费区间 -->
    <div class="filter-container">
      <el-button
        class="filter-item"
        type="primary"
        :icon="Refresh"
        @click="handleFilter"
        >刷新</el-button
      >
      <el-button class="filter-item" type="primary" @click="handleAdd">新增角色</el-button>
    </div>

    <!-- 查询结果 -->
    <el-table
      ref="table"
      v-loading="listLoading"
      :data="list"
      element-loading-text="正在查询中。。。"
      :height="tableHeight() + 4"
      border
      fit
      highlight-current-row
      style="width: 100%"
    >
      <el-table-column
        align="center"
        min-width="250"
        label="角色ID"
        prop="id"
      />
      <el-table-column
        align="center"
        min-width="250"
        label="角色名称"
        prop="name"
      >
       
      </el-table-column>
 

      <el-table-column
        align="center"
        label="操作"
        min-width="250"
        class-name="small-padding fixed-width"
        fixed="right"
      >
        <template #default="scope">          
          <el-button type="primary" size="small" @click="handleEdit(scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDelete(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <div class="pageHolder">
      <el-pagination
        background
        v-model:page-size="listQuery.limit"
        layout="total,sizes, prev, pager, next, jumper"
        :total="total"
        @current-change="pageChange"
        @size-change="handleSizeChange"
      />
    </div>

    

     <!-- 新增/编辑角色对话框 -->
    <el-dialog 
      v-model="dialogVisible" 
      :title="dialogTitle" 
      width="50%"
    >
      <el-form :model="roleForm" label-width="100px">
        <el-form-item label="角色ID" required v-if="isAdd">
          <el-input v-model="roleForm.id" placeholder="请输入角色名称" />
        </el-form-item>

        <el-form-item label="角色ID" required v-if="isEdit">
          <el-input v-model="roleForm.id"  readonly/>
        </el-form-item>

        <el-form-item label="角色名称" required>
          <el-input v-model="roleForm.name" placeholder="请输入角色名称" />
        </el-form-item>
        
        <el-form-item label="授权菜单" required>
          <el-tree
            ref="menuTree"
            :data="menuOptions"
            show-checkbox
            node-key="id"
            default-expand-all	
            :props="defaultProps"
          />
        </el-form-item>
      </el-form>
      
      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="submitForm">确认</el-button>
      </template>
    </el-dialog>

   
  </div>
</template>

 
<script setup lang="ts">
import { tableHeight } from "@/util/index.ts";
import configs from "@/util/config.ts";
import http from "@/api/js/http";

import { ref, reactive, onMounted,nextTick } from "vue";
import msg from "@/util/Message.ts";
import { Refresh } from "@element-plus/icons-vue";
import { ElMessage } from 'element-plus'
import  {type ISysMenu} from '@/types/index.ts'

const dialogVisible = ref(false)
const dialogTitle = ref('新增角色')
const menuTree = ref(null)

const roleForm = reactive({
  id: null,
  name: '',
  menus: []
})

const list = ref<any>([]);
const isEdit = ref(false)
const isAdd = ref(false)
const total = ref<number>(0);
const listLoading = ref(true);
const listQuery = reactive({
  page: 1,
  durationCode: null,
  limit: configs.limit,
});

const defaultProps = {
  children: 'children',
  label: 'name'
}

const menuOptions = ref([
  {
    id: 1,
    label: '系统管理',
    children: [
      { id: 2, label: '角色管理' },
      { id: 3, label: '用户管理' }
    ]
  }
])



onMounted(() => {
  getAllMenuList();
  getList();
});


function pageChange(page: number) {
  listQuery.page = page;
  getList();
}

 

// 打开编辑对话框
//@ts-ignore
const handleEdit = (row) => {
  dialogTitle.value = '编辑角色'
  //currentRoleId.value = row.id
  roleForm.id = row.id
  roleForm.name = row.name
  isEdit.value = true;
  isAdd.value = false;
  dialogVisible.value = true


  loadRoleMenus(row.id);  
}

const loadRoleMenus = (id:string)=>{

  http.get('/admin/permission/getRoleMenus',{
    roleId:id
  }).then((resp)=>{

    var data = resp.data;
    //@ts-ignore
    var menus = [];
//@ts-ignore
    data.forEach((item)=>{
      menus.push(item.menuId)
    })

    nextTick(() => {
      //@ts-ignore
      menuTree.value.setCheckedKeys(menus)
    })


  })

  
}



// 打开新增对话框
const handleAdd = () => {
  dialogTitle.value = '新增角色'
  roleForm.id = null
  roleForm.name = ''
  dialogVisible.value = true
  isAdd.value= true;
  isEdit.value=false;
  nextTick(() => {
    //@ts-ignore
    menuTree.value.setCheckedKeys([])
  })
}
 
 

function handleSizeChange() {
  getList();
}




function getAllMenuList() {
  listLoading.value = true;

  http
    .get<ISysMenu[]>("/admin/permission/allMenuList")
    .then((resp) => {
      var respList = resp?.data;
      //@ts-ignore
      if(respList)menuOptions.value = respList;
    });
      
}

function getList() {
  listLoading.value = true;

  http
    .get("/admin/permission/roleList")
    .then((resp) => {
      var respList = resp?.data;
      list.value = respList;
      listLoading.value = false;
      //@ts-ignore
      total.value = respList.length;
    })
    .catch(() => {
      list.value = [];
      total.value = 0;
      listLoading.value = false;
    });
}

function handleFilter() {
  listQuery.page = 1;
  getList();
}

function handleDelete(row: any) {
  msg.delConfirm().then(() => {
    doDelete(row);
  });
}

function doDelete(row: any) {
  var data = "roleId=" + row.id;

  http
    .post("/admin/permission/deleteRole", data)
    .then(() => {
      msg.success("删除成功");
      getList();
    })
    .catch(() => {
      msg.error("删除失败");
    });
}

 
 
// 提交表单
const submitForm = () => {
  if (!roleForm.name) {
    ElMessage.warning('请输入角色名称')
    return
  }
  //@ts-ignore
  const checkedKeys = menuTree.value.getCheckedKeys()
  
  //@ts-ignore
  var menuList = [];
  //@ts-ignore
  checkedKeys.forEach(element => {
    menuList.push({
      id:element
    })
  });

  //@ts-ignore
  roleForm.menuList = menuList;

  http.post('/admin/permission/saveRole',roleForm)
  .then((resp)=>{
    if(resp.code == 0){
      ElMessage.success('新增成功')
      dialogVisible.value = false
      getList();
    }else{
      msg.error(resp.msg);
    }
    
  });

 
  
}
</script>
